package com.kiven.http;

import java.io.File;
import java.io.FileOutputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.HttpURLConnection;
/**
 * 发送Http请求的类
 * @author liqingwen
 *
 */

public class HttpService {
	private static int BUFFER_SIZE = 4096;
	
	/**
	 * 发送请求下载文件<br>
	 * Example:<br><br>
	 * String baseUrl="http://localhost:8080/";<br>
	 * String path="home/lijianbo/kivenTest/Race/temp/status";<br>
	 * String fileName="Race_1_0_0_status.xml.zip";<br>
	 * 
	 * @param baseUrl 
	 * @param path
	 * @param fileName
	 */
	public void send(String baseUrl,String path,String fileName) {
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		HttpURLConnection httpConnection = null;
		URL url = null;
		
		byte[] buf = new byte[BUFFER_SIZE];
		int size=0;
		
		try {
			url = new URL(baseUrl + fileName);
			httpConnection = (HttpURLConnection)url.openConnection();
			httpConnection.connect();
			
			bis = new BufferedInputStream(httpConnection.getInputStream());
			fos = new FileOutputStream(path + File.separator + fileName);
			
			//读并写入文件
			while((size = bis.read(buf)) != -1) {
				fos.write(buf, 0, size);
			}
			
			fos.close();
			bis.close();
			httpConnection.disconnect();
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
